<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';

import { useAccess } from '@vben/access';
import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { addFullName, cloneDeep, getPopupContainer } from '@vben/utils';

import { Modal } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import {
  issueReceiptRecordsAdd,
  issueReceiptRecordsInfo,
  issueReceiptRecordsUpdate,
} from '#/api/hm/issueReceiptRecords';
import { deptList } from '#/api/system/dept';
import { getDeptTree } from '#/api/system/user';

import { modalSchema } from './data';

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const isAgainUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : '出入库';
});

const { hasAccessByRoles } = useAccess();
const isAdmin = computed(() => {
  return hasAccessByRoles(['admin', 'superadmin', 'ceo', 'warehouse-manage']);
});

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    // 默认占满两列
    formItemClass: 'col-span-2',
    // 默认label宽度 px
    labelWidth: 80,
    // 通用配置项 会影响到所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  schema: modalSchema(),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

const [BasicModal, modalApi] = useVbenModal({
  draggable: true,
  fullscreenButton: false,
  onCancel: handleCancel,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const { id, isAgain } = modalApi.getData() as {
      id?: number | string;
      isAgain?: boolean;
    };
    isUpdate.value = !!id;
    isAgainUpdate.value = isAgain ?? false;
    if (isUpdate.value && id) {
      const record = await issueReceiptRecordsInfo(id);
      await formApi.setValues(record);
    }

    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.modalLoading(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    Modal.confirm({
      title: '提示',
      okType: 'danger',
      content: `请核对信息是否正确，确定提交吗？`,
      onOk: async () => {
        // getValues获取为一个readonly的对象 需要修改必须先深拷贝一次
        const data = cloneDeep(await formApi.getValues());
        if (isAgainUpdate.value) {
          data.status = 'WCL';
          data.isAgain = true;
        } else {
          data.isAgain = false;
        }
        await (isUpdate.value
          ? issueReceiptRecordsUpdate(data)
          : issueReceiptRecordsAdd(data));
        emit('reload');
        await handleCancel();
      },
    });
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.modalLoading(false);
  }
}

async function handleCancel() {
  modalApi.close();
  await formApi.resetForm();
}

// 出库入库店铺Schema 更新
onMounted(async () => {
  const requestParams = { ancestors: '101', deptCategory: '' };
  if (isAdmin.value) {
    requestParams.deptCategory = '';
  }
  const deptTree = await deptList(requestParams);
  const deptOptions = [];
  const deptTransOptions = deptTree.map((item) => ({
    label: item.deptName,
    value: item.deptId.toString(),
  }));
  deptOptions.push(...deptTransOptions);
  formApi.updateSchema([
    {
      fieldName: 'recordStartLocation',
      componentProps: {
        options: deptOptions,
        showSearch: true,
        optionFilterProp: 'label',
      },
    },
    {
      fieldName: 'recordEndLocation',
      componentProps: {
        options: deptOptions,
        showSearch: true,
        optionFilterProp: 'label',
      },
    },
  ]);
});

// 初始化部门选择
onMounted(async () => {
  await setupDeptSelect();
});

async function setupDeptSelect() {
  // updateSchema
  const deptTree = await getDeptTree();
  // 选中后显示在输入框的值 即父节点 / 子节点
  addFullName(deptTree, 'label', ' / ');
  formApi.updateSchema([
    {
      componentProps: (formModel) => ({
        class: 'w-full',
        fieldNames: {
          key: 'id',
          value: 'id',
          children: 'children',
        },
        async onSelect() {
          /** 变化后需要重新选择岗位 */
          formModel.employeeIds = [];
        },
        getPopupContainer,
        placeholder: '请选择',
        showSearch: true,
        treeData: deptTree,
        treeDefaultExpandAll: true,
        treeLine: { showLeafIcon: false },
        // 筛选的字段
        treeNodeFilterProp: 'label',
        // 选中后显示在输入框的值
        treeNodeLabelProp: 'fullName',
      }),
      fieldName: 'deptId',
    },
  ]);
}
</script>

<template>
  <BasicModal :close-on-click-modal="false" :title="title" class="w-[600px]">
    <BasicForm />
  </BasicModal>
</template>
